#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
系统内置配置 - 不可修改的基础配置
包含所有语言关键字、系统API、类型等
"""

class BuiltinConfigDefine:
    """系统内置配置 - 只读"""
    
    # 语言关键字 (绝对不能混淆)
    LANGUAGE_KEYWORDS = {
        'swift': [
            # 基础关键字
            'self', 'super', 'nil', 'true', 'false', 'Self', 'Type', 'Protocol',
            
            # 声明关键字
            'class', 'struct', 'enum', 'protocol', 'extension', 'func', 'var', 'let',
            'init', 'deinit', 'required', 'convenience', 'override', 'final', 'static',
            
            # 访问控制
            'private', 'public', 'internal', 'open', 'fileprivate',
            
            # 属性包装器和修饰符
            'lazy', 'weak', 'unowned', 'mutating', 'nonmutating', 'dynamic',
            
            # 控制流
            'if', 'else', 'switch', 'case', 'default', 'for', 'in', 'while', 'repeat',
            'break', 'continue', 'return', 'guard', 'defer', 'do', 'try', 'catch', 'throw',
            
            # 类型相关
            'is', 'as', 'Any', 'AnyObject', 'typealias', 'associatedtype', 'some',
            
            # 其他
            'import', 'operator', 'precedencegroup', 'infix', 'prefix', 'postfix',
            'where', 'inout', 'throws', 'rethrows'
        ],
        
        'objc': [
            # 基础关键字
            'self', 'super', 'nil', 'NULL', 'Nil', 'YES', 'NO', 'TRUE', 'FALSE',
            'id', 'Class', 'SEL', 'IMP', '_cmd',
            
            # 内存管理
            'alloc', 'init', 'dealloc', 'new', 'copy', 'mutableCopy',
            'retain', 'release', 'autorelease', 'retainCount',
            
            # 类型关键字
            'void', 'BOOL', 'bool', 'char', 'int', 'short', 'long', 'float', 'double',
            'signed', 'unsigned', 'const', 'static', 'extern', 'inline', 'volatile',
            
            # 控制流
            'if', 'else', 'switch', 'case', 'default', 'for', 'while', 'do',
            'break', 'continue', 'return', 'goto',
            
            # 结构
            'struct', 'union', 'enum', 'typedef',
            
            # 预处理器
            'define', 'undef', 'include', 'import', 'ifdef', 'ifndef', 'endif',
            'if', 'elif', 'else', 'pragma'
        ],
        
        'kotlin': [
            # 基础关键字
            'this', 'super', 'null', 'true', 'false',
            
            # 声明关键字
            'class', 'interface', 'object', 'enum', 'fun', 'val', 'var',
            'data', 'sealed', 'abstract', 'open', 'final', 'override',
            'companion', 'inline', 'reified', 'crossinline', 'noinline', 'suspend',
            
            # 访问修饰符
            'private', 'protected', 'public', 'internal',
            
            # 类型相关
            'is', 'as', 'in', 'out', 'by', 'where', 'typealias',
            
            # 控制流
            'if', 'else', 'when', 'for', 'while', 'do', 'break', 'continue', 'return',
            'try', 'catch', 'finally', 'throw',
            
            # 其他
            'import', 'package', 'constructor', 'init', 'field', 'property',
            'get', 'set', 'receiver', 'param', 'setparam', 'delegate'
        ],
        
        'java': [
            # 基础关键字
            'this', 'super', 'null', 'true', 'false',
            
            # 类型关键字
            'void', 'boolean', 'byte', 'char', 'short', 'int', 'long', 'float', 'double',
            
            # 声明关键字
            'class', 'interface', 'enum', 'abstract', 'final', 'static',
            'extends', 'implements', 'native', 'strictfp', 'synchronized', 'transient', 'volatile',
            
            # 访问修饰符
            'private', 'protected', 'public',
            
            # 控制流
            'if', 'else', 'switch', 'case', 'default', 'for', 'while', 'do',
            'break', 'continue', 'return', 'try', 'catch', 'finally', 'throw', 'throws',
            
            # 对象相关
            'new', 'instanceof', 'const', 'goto',
            
            # 包和导入
            'import', 'package',
            
            # 其他
            'assert', 'var'  # var是Java 10+的局部变量类型推断
        ]
    }
    
    # 系统类型 (不应混淆)
    SYSTEM_TYPES = [
        # 通用集合类型
        'List', 'ArrayList', 'LinkedList', 'Vector',
        'Map', 'HashMap', 'TreeMap', 'LinkedHashMap', 'ConcurrentHashMap',
        'Set', 'HashSet', 'TreeSet', 'LinkedHashSet',
        'Queue', 'Deque', 'PriorityQueue', 'ArrayDeque',
        'Collection', 'Iterable', 'Iterator', 'ListIterator',
        'Array', 'Dictionary',
        
        # iOS系统类型
        'NSArray', 'NSMutableArray', 'NSDictionary', 'NSMutableDictionary',
        'NSSet', 'NSMutableSet', 'NSOrderedSet', 'NSMutableOrderedSet',
        'NSString', 'NSMutableString', 'NSAttributedString', 'NSMutableAttributedString',
        'NSNumber', 'NSDecimalNumber', 'NSDate', 'NSCalendar', 'NSDateFormatter',
        'NSData', 'NSMutableData', 'NSURL', 'NSURLRequest', 'NSMutableURLRequest',
        'NSURLSession', 'NSTimeInterval', 'NSError', 'NSException', 'NSNotification', 'NSNotificationCenter',
        'NSBundle', 'NSFileManager', 'NSUserDefaults', 'NSThread', 'NSOperation',
        'NSOperationQueue', 'NSTimer', 'NSRunLoop', 'NSLock', 'NSCondition',
        
        # UIKit类型
        'UIView', 'UIViewController', 'UIWindow', 'UIApplication', 'UIScene',
        'UILabel', 'UIButton', 'UIImageView', 'UITextField', 'UITextView',
        'UITableView', 'UITableViewCell', 'UICollectionView', 'UICollectionViewCell',
        'UINavigationController', 'UITabBarController', 'UIAlertController',
        
        # 基础类型包装类
        'String', 'Integer', 'Boolean', 'Double', 'Float', 'Long', 'Short', 'Byte', 'Character',
        'Number', 'Object', 'Class', 'Enum', 'Comparable', 'Serializable', 'Cloneable',
        
        # Kotlin特有类型
        'Unit', 'Nothing', 'Any', 'Function', 'KClass', 'KFunction', 'KProperty',
        'Pair', 'Triple', 'Lazy', 'Sequence', 'Regex', 'Result'
    ]
    
    # 系统方法 (不应混淆)
    SYSTEM_METHODS = [
        # Object/NSObject 基础方法
        'toString', 'equals', 'hashCode', 'clone', 'finalize', 'getClass',
        'notify', 'notifyAll', 'wait',
        'description', 'debugDescription', 'hash', 'isEqual',
        'respondsToSelector', 'performSelector', 'isKindOfClass', 'isMemberOfClass',
        'conformsToProtocol', 'doesNotRecognizeSelector',
        
        # 集合通用方法
        'add', 'remove', 'clear', 'contains', 'isEmpty', 'size', 'count',
        'get', 'set', 'put', 'putAll', 'keySet', 'values', 'entrySet',
        'addAll', 'removeAll', 'retainAll', 'containsAll',
        'toArray', 'iterator', 'listIterator',
        
        # NSArray/NSMutableArray
        'addObject', 'removeObject', 'removeAllObjects', 'objectAtIndex',
        'firstObject', 'lastObject', 'containsObject', 'indexOfObject',
        'insertObject', 'replaceObjectAtIndex',
        
        # NSDictionary/NSMutableDictionary
        'objectForKey', 'setObject', 'removeObjectForKey', 'allKeys', 'allValues',
        'objectForKeyedSubscript', 'setObjectForKeyedSubscript',
        
        # NSString
        'length', 'characterAtIndex', 'substringToIndex', 'substringFromIndex',
        'substringWithRange', 'stringByAppendingString', 'stringByAppendingFormat',
        'componentsSeparatedByString', 'uppercaseString', 'lowercaseString',
        
        # 系统生命周期方法
        'cancel', 'resume', 'suspend', 'invalidate', 'start', 'stop', 'pause',
        'play', 'reset', 'reload', 'refresh', 'update', 'configure',
        
        # 内存管理
        'retain', 'release', 'autorelease', 'dealloc',
        
        # 编码解码
        'encode', 'decode', 'encodeWithCoder', 'initWithCoder',
        'encodeObject', 'decodeObject', 'encodeInt', 'decodeInt',
        
        # 复制
        'copy', 'mutableCopy', 'copyWithZone', 'mutableCopyWithZone',
        
        # 比较
        'compare', 'isEqualToString', 'isEqualToNumber', 'isEqualToDate',
        'compareTo', 'compareToIgnoreCase'
    ]
    
    # 系统前缀 (识别系统API)
    SYSTEM_PREFIXES = {
        'ios': [
            # Foundation & Core
            'NS', 'CF', 'CG', 'CT', 'CI', 'CM', 'CA', 'CV',
            # UIKit & Views
            'UI', 'WK', 'PK', 'SC', 'AR', 'RK',
            # Media & Graphics
            'AV', 'AL', 'GL', 'MTL', 'MTK', 'SCN', 'SK', 'VN',
            # Network & Web
            'NW', 'WK',
            # Maps & Location
            'MK', 'CL', 'CN',
            # Health & Fitness
            'HK', 'HM',
            # Authentication & Security
            'LA', 'AS', 'SF',
            # Store & Cloud
            'SK', 'CK', 'IC',
            # Photos & Camera
            'PH', 'AV',
            # Messages & Social
            'MF', 'SL', 'TW', 'AC',
            # Other Frameworks
            'AB', 'EK', 'GK', 'MP', 'QC', 'QL'
        ],
        'android': [
            'android', 'java', 'javax', 'kotlin', 'kotlinx',
            'androidx', 'com.google', 'dalvik', 'org.apache',
            'org.json', 'org.xml', 'org.w3c'
        ]
    }
    
    # 生命周期方法模式
    LIFECYCLE_PATTERNS = {
        'ios': [
            # UIViewController
            r'^(viewDid|viewWill)',
            r'^(loadView|viewDidLoad|viewWillAppear|viewDidAppear)',
            r'^(viewWillDisappear|viewDidDisappear|viewWillUnload|viewDidUnload)',
            r'^(viewWillLayoutSubviews|viewDidLayoutSubviews)',
            r'^(didReceiveMemoryWarning|traitCollectionDidChange)',
            
            # UIApplication
            r'^(application|scene)',
            r'^(applicationDid|applicationWill)',
            
            # UITableView/UICollectionView
            r'^(tableView|collectionView)',
            r'^(numberOfSections|numberOfRows|numberOfItems)',
            r'^(cellForRow|cellForItem)',
            r'^(didSelectRow|didSelectItem)',
            
            # UIView
            r'^(awakeFromNib|prepare|layoutSubviews|drawRect)',
            r'^(touchesBegan|touchesMoved|touchesEnded|touchesCancelled)',
            
            # Delegate patterns
            r'.*Delegate$',
            r'.*DataSource$',
            
            # KVO/KVC
            r'^(observeValueForKeyPath|setValue|valueForKey)',
            
            # Core Data
            r'^(managedObjectContext|persistentStoreCoordinator)',
            
            # Notifications
            r'.*Notification$'
        ],
        
        'android': [
            # Activity lifecycle
            r'^on(Create|Start|Resume|Pause|Stop|Destroy|Restart)',
            r'^on(SaveInstanceState|RestoreInstanceState)',
            r'^on(NewIntent|ActivityResult|RequestPermissionsResult)',
            
            # Fragment lifecycle
            r'^on(Attach|Create|CreateView|ViewCreated|ActivityCreated)',
            r'^on(Start|Resume|Pause|Stop|DestroyView|Destroy|Detach)',
            
            # View lifecycle
            r'^on(Measure|Layout|Draw|SizeChanged|Visibility)',
            r'^on(Touch|Click|LongClick|Focus|Key)',
            r'^on(Scroll|Fling|Scale|Gesture)',
            
            # Service lifecycle
            r'^on(StartCommand|Bind|Unbind|TaskRemoved)',
            
            # BroadcastReceiver
            r'^on(Receive)',
            
            # Adapter methods
            r'^(getCount|getItem|getItemId|getView|getViewType)',
            
            # Common callbacks
            r'^on(Success|Error|Complete|Progress|Cancel)',
            r'^on(Response|Failure)',
            
            # AsyncTask (deprecated but still used)
            r'^(doInBackground|onPreExecute|onPostExecute|onProgressUpdate)'
        ]
    }
    
    # 常用注解 (不应混淆)
    COMMON_ANNOTATIONS = {
        'java': [
            'Override', 'Deprecated', 'SuppressWarnings', 'SafeVarargs',
            'FunctionalInterface', 'Retention', 'Target', 'Inherited',
            'Documented', 'Repeatable'
        ],
        'kotlin': [
            'JvmStatic', 'JvmField', 'JvmName', 'JvmOverloads', 'JvmSynthetic',
            'Throws', 'Volatile', 'Synchronized', 'Strictfp', 'Transient'
        ],
        'android': [
            'NonNull', 'Nullable', 'Keep', 'Proguard', 'VisibleForTesting',
            'MainThread', 'WorkerThread', 'UiThread', 'BindingAdapter',
            'Inject', 'Singleton', 'Module', 'Component', 'Provides'
        ]
    }
    
    @classmethod
    def get_all_reserved_symbols(cls) -> set:
        """获取所有保留符号的集合"""
        reserved = set()
        
        # 添加所有语言关键字
        for lang_keywords in cls.LANGUAGE_KEYWORDS.values():
            reserved.update(lang_keywords)
        
        # 添加系统类型和方法
        reserved.update(cls.SYSTEM_TYPES)
        reserved.update(cls.SYSTEM_METHODS)
        
        # 添加注解
        for annotations in cls.COMMON_ANNOTATIONS.values():
            reserved.update(annotations)
        
        return reserved
    
    @classmethod
    def is_system_prefix(cls, symbol: str, platform: str) -> bool:
        """检查符号是否以系统前缀开头"""
        prefixes = cls.SYSTEM_PREFIXES.get(platform, [])
        return any(symbol.startswith(prefix) for prefix in prefixes)
    
    @classmethod
    def matches_lifecycle_pattern(cls, symbol: str, platform: str) -> bool:
        """检查符号是否匹配生命周期模式"""
        import re
        patterns = cls.LIFECYCLE_PATTERNS.get(platform, [])
        return any(re.match(pattern, symbol) for pattern in patterns)

    # 第三方库定义
    THIRD_PARTY_LIBRARIES = {
        'ios': {
            # 网络库
            'AFNetworking', 'Alamofire', 'Moya',
            # 图片加载
            'SDWebImage', 'Kingfisher',
            # 布局
            'SnapKit', 'Masonry',
            # 提示框
            'MBProgressHUD', 'SVProgressHUD',
            # 下拉刷新
            'MJRefresh',
            # 键盘
            'IQKeyboardManager',
            # 工具库
            'YYKit', 'SwiftyJSON', 'ObjectMapper', 'HandyJSON',
            # 响应式
            'RxSwift', 'RxCocoa', 'ReactiveCocoa',
            # 数据库
            'FMDB', 'Realm', 'SQLite.swift',
            # 图表
            'Charts',
            # 分析/崩溃
            'Firebase', 'Crashlytics', 'Fabric', 'Bugly',
            # 推送/统计
            'JPush', 'UMeng', 'TalkingData', 'GrowingIO',
            # 动画
            'Lottie', 'Hero', 'Spring', 'pop',
            # 日志
            'CocoaLumberjack', 'SwiftyBeaver', 'XCGLogger'
        },
        'android': {
            # 网络库
            'Retrofit', 'OkHttp', 'Volley',
            # JSON解析
            'Gson', 'Jackson', 'Moshi',
            # 图片加载
            'Glide', 'Picasso', 'Fresco', 'Coil', 'UniversalImageLoader',
            # 视图绑定
            'ButterKnife', 'ViewBinding', 'DataBinding',
            # 依赖注入
            'Dagger', 'Hilt', 'Koin', 'Kodein',
            # 响应式
            'RxJava', 'RxAndroid', 'RxKotlin', 'Coroutines',
            # 事件总线
            'EventBus', 'Otto', 'LiveData', 'Flow',
            # 数据库
            'Room', 'GreenDAO', 'Realm', 'ObjectBox', 'SQLDelight',
            # 调试工具
            'LeakCanary', 'Stetho', 'Chuck', 'Timber',
            # 图表
            'MPAndroidChart', 'GraphView', 'HelloCharts',
            # 动画
            'Lottie', 'AndroidViewAnimations', 'RecyclerViewAnimators',
            # 多媒体
            'ZXing', 'CameraX', 'ExoPlayer', 'Vitamio',
            # 分析/崩溃
            'Firebase', 'Crashlytics', 'Bugsnag', 'ACRA',
            # 推送
            'OneSignal', 'PushWoosh', 'FCM', 'JPush',
            # 第三方SDK
            'Facebook', 'Twitter', 'Google', 'WeChat', 'Alipay'
        }
    }

    # 第三方库的排除规则
    LIBRARY_EXCLUSION_RULES = {
        # iOS库
        'AFNetworking': {'prefixes': ['AF']},
        'Alamofire': {'prefixes': ['Alamofire']},
        'SDWebImage': {'prefixes': ['SD']},
        'Kingfisher': {'prefixes': ['KF', 'Kingfisher']},
        'SnapKit': {'prefixes': ['Snap', 'Constraint']},
        'Masonry': {'prefixes': ['MAS']},
        'RxSwift': {'prefixes': ['Rx', 'Observable', 'Subject']},
        'Firebase': {'prefixes': ['FIR', 'Firebase']},
        'Realm': {'prefixes': ['RLM', 'Realm']},

        # Android库
        'Retrofit': {'prefixes': ['retrofit2']},
        'OkHttp': {'prefixes': ['okhttp3']},
        'Glide': {'prefixes': ['com.bumptech.glide']},
        'Dagger': {'prefixes': ['dagger']},
        'Hilt': {'prefixes': ['hilt', 'dagger.hilt']},
        'RxJava': {'prefixes': ['io.reactivex', 'rx']},
        'Room': {'prefixes': ['androidx.room']},
        'Gson': {'prefixes': ['com.google.gson']},
        'EventBus': {'prefixes': ['org.greenrobot.eventbus']},
        'LeakCanary': {'prefixes': ['leakcanary', 'com.squareup.leakcanary']}
    }

    @classmethod
    def get_third_party_libs(cls, platform: str) -> set:
        """获取指定平台的第三方库列表"""
        return cls.THIRD_PARTY_LIBRARIES.get(platform, set())

    @classmethod
    def get_library_exclusion_rules(cls, library_name: str) -> dict:
        """获取指定库的排除规则"""
        return cls.LIBRARY_EXCLUSION_RULES.get(library_name, {})
